package cn.com.miao.lynx.plugin.sms.service.impl;

import cn.com.miao.lynx.common.core.excpetion.LynxException;
import cn.com.miao.lynx.plugin.sms.model.SmsRequest;
import cn.com.miao.lynx.plugin.sms.model.SmsResponse;
import cn.com.miao.lynx.plugin.sms.service.SmsService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

/**
 * AliyunSmsService
 *
 * @title: AliyunSmsService
 * @description:
 * @author: dengmiao
 * @create: 2020-01-10 11:27
 **/
@Slf4j
@Builder
@AllArgsConstructor
public class AliyunSmsService implements SmsService {

    /**
     * 阿里云国际短信产品名称
     */
    private static final String ALIYUN_PRODUCT = "Dysmsapi";
    /**
     * 阿里云国际短信产品域名
     */
    private static final String ALIYUN_PRODUCT_DOMAIN = "dysmsapi.aliyuncs.com";
    /**
     * 发送成功后返回code
     */
    private static final String SUCCESS_RESULT = "OK";
    /**
     * RAM账号的AccessKey ID
     */
    private String accessKeyId;
    /**
     * RAM账号Access Key Secret
     */
    private String accessKeySecret;
    /**
     * 短信签名
     */
    private String signName;
    /**
     * 短信环境
     */
    private String profile;
    /**
     * 短信发送连接超时时长
     */
    private long connectionTimeout;
    /**
     * 短信接收消息连接超时时长
     */
    private long readTimeout;

    @PostConstruct
    public void _init() {
        System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(this.connectionTimeout));
        System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(this.readTimeout));
    }

    @Override
    public SmsResponse send(SmsRequest request) throws LynxException {
        try {
            IClientProfile profile = DefaultProfile.getProfile(this.profile, this.accessKeyId, this.accessKeySecret);
            DefaultProfile.addEndpoint(this.profile, ALIYUN_PRODUCT, ALIYUN_PRODUCT_DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(request.getPhone());
            sendSmsRequest.setSignName(this.signName);
            sendSmsRequest.setTemplateCode(request.getTemplateCode());
            sendSmsRequest.setTemplateParam(request.getParam().getParamJson());

            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest);

            return SmsResponse.builder()
                    .success(SUCCESS_RESULT.equals(sendSmsResponse.getCode()))
                    .code(sendSmsResponse.getCode())
                    .build();

        } catch (Exception e) {
            throw new LynxException("短信验证码发送送异常" + e.getMessage());
        }
    }
}
